import md5 from "js-md5";
import { Login } from "@/network/login/";
import {
    setCookie,
    getCookie,
    removeCookie,
    // , removeCookie
} from "@/utils/support";

//管理用户相关的状态值
const user = {
    state: {
        name: getCookie("name"), //登录后的用户的中文名   保存在 cookie
        roleid: getCookie("roleid"), //1超级管理员 2 普通用户   保存在 cookie
    },
    mutations: {
        //设置 中文名
        SET_NAME: (state, name) => {
            state.name = name;
        },
        //设置角色id
        SET_ROLEID: (state, roleid) => {
            state.roleid = roleid;
        },
    },
    actions: {
        //登录动作 context ={commit,state}
        LoginAC({ commit }, userInfo) {
            return new Promise((resolve) => {
                console.log("login29", userInfo);
                const { username, password } = userInfo;
                //1.密码 加密
                userInfo.password = md5(password + md5(password).substr(10, 10) + 2014);
                Login(userInfo).then((res) => {
                    console.log("res:", res);
                    if (res.status == 200) {
                        setCookie("token", res["token"], 1);
                        setCookie("name", res["name"], 1);
                        setCookie("username", res["username"], 1);
                        setCookie("roleid", res["roleid"], 1);

                        commit("SET_NAME", res["name"]);
                        commit("SET_ROLEID", res["roleid"]);

                        resolve(res);
                    }
                });
            });
        },
        LogoutAC({ commit }) {
            commit("SET_NAME", "");
            commit("SET_ROLEID");
            removeCookie("token");
            removeCookie("name");
            removeCookie("username");
            removeCookie("roleid");
        },
    },
};
export default user;
